package thread;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description:
 * @Param:
 * @return:
 * @Author: cuihao
 * @Date: 2019/9/11
 */
public class ThreadLocalDemo {

    Random random = new Random();
    private final ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 5;
        }
    };

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        ThreadLocalDemo tld = new ThreadLocalDemo();
        executorService.execute(tld.new ThreadA());
        executorService.execute(tld.new ThreadA());
        executorService.execute(tld.new ThreadA());
        executorService.execute(tld.new ThreadA());
    }

    public class ThreadA implements Runnable {
        @Override
        public void run() {
            Integer lint = threadLocal.get();
            lint = random.nextInt(100);
            System.out.println(java.lang.Thread.currentThread().getName() + "-" + lint);

            threadLocal.set(lint);
            System.out.println(java.lang.Thread.currentThread().getName() + "-" + threadLocal.get());

            threadLocal.remove();
            lint = lint + 100;
            threadLocal.set(lint);
            System.out.println(java.lang.Thread.currentThread().getName() + "-" + threadLocal.get());


        }
    }
}


/*
*
*
* 输出结果为：
*
*
pool-1-thread-2-37
pool-1-thread-4-96
pool-1-thread-3-42
pool-1-thread-1-97
pool-1-thread-3-42
pool-1-thread-4-96
pool-1-thread-2-37
pool-1-thread-3-142
pool-1-thread-1-97
pool-1-thread-2-137
pool-1-thread-4-196
pool-1-thread-1-197

可以看到多个线程并发执行，每个线程会打印三次日志，而且每个线程内部的打印的是一致的，不会因为其他的线程修改而改变值
*
*
*
*
* */